﻿using System;
using System.Windows;
using System.Threading;
using System.ServiceModel;
using System.Windows.Input;
using System.Windows.Controls;
using System.ServiceModel.Discovery;

using Builderator.Core.Interfaces;

namespace Builderator.Firefly
{
    /// <summary>
    /// Interaction logic for DomainBrowserWindow.xaml
    /// </summary>
    public partial class DomainBrowserWindow : Window
    {
        public string Selected
        {
            get;
            set;
        }

        public DomainBrowserWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            Thread thread = new Thread(delegate()
                {
                    DiscoveryClient discovery = new DiscoveryClient(new UdpDiscoveryEndpoint());

                    FindResponse response = discovery.Find(new FindCriteria(typeof(IBuilderatorEngine)));

                    foreach (EndpointDiscoveryMetadata metadata in response.Endpoints)
                    {
                        this.Dispatcher.Invoke(new Action(delegate
                            {
                                this.serverListBox.Items.Add(metadata.Address.Uri.Host);
                            }));
                    }

                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        this.Cursor = Cursors.Arrow;
                    }));
                });

            thread.Start();
        }

        private void selectButton_Click(object sender, RoutedEventArgs e)
        {
            this.Selected = this.serverListBox.SelectedItem as string;

            this.DialogResult = true;
        }
    }
}
